import { Secret, User, Book, Setting } from '../models';
import shortid from 'shortid';

export default function (router) {
  router.get('/api/admin/secret', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    let { page, limit, search } = ctx.parsePageAndLimit(ctx.request.query);
    if (!search) {
      search = '';
    }

    const total = await Secret.countDocuments().populate({
      path: 'userid',
      select: 'username',
      match: {
        username: new RegExp(search, 'i')
      }
    });
    const users = await Secret.find()
      .populate({
        path: 'userid',
        select: 'username',
        match: {
          username: new RegExp(search, 'i')
        }
      })
      .populate({
        path: 'bookid',
        select: 'name'
      })
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ active: 1, create_time: -1 });
    await ctx.json(true, '获取秘钥列表成功', { list: users, total });
  });

  router.post('/api/admin/secret', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    let { userid, bookid } = ctx.request.body;
    // 校验id合法性
    const thisUser = await User.findById(userid, '_id');
    if (!thisUser) {
      await ctx.json(false, '用户不存在');
      return false;
    }
    const thisBook = await Book.findById(bookid, '_id');
    if (!thisBook) {
      await ctx.json(false, '书籍不存在');
      return false;
    }
    const newSecret = await Secret.create({
      // @ts-ignore
      userid: ctx.transId(userid),
      bookid: ctx.transId(bookid),
      secret: shortid.generate(),
      active: false,
      create_time: new Date()
    });
    await ctx.json(true, '创建秘钥成功', newSecret);
  });

  router.put('/api/admin/secret/:id', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    let { userid, bookid, active, secret } = ctx.request.body;
    let id = ctx.params.id;

    // 校验id合法性
    const thisUser = await User.findById(userid, '_id');
    if (!thisUser) {
      await ctx.json(false, '用户不存在');
      return false;
    }

    const thisBook = await Book.findById(bookid, '_id');
    if (!thisBook) {
      await ctx.json(false, '书籍不存在');
      return false;
    }

    const thisSecret = await Secret.findById(id, '_id');
    if (!thisSecret) {
      await ctx.json(false, '秘钥不存在');
      return false;
    }

    const secretReg = /^[A-Za-z0-9_-]{7,14}$/;
    if (!secretReg.test(secret)) {
      await ctx.json(false, '秘钥格式错误');
      return false;
    }

    const updateResult = await Secret.updateOne(
      { _id: id },
      {
        $set: {
          userid: ctx.transId(userid),
          bookid: ctx.transId(bookid),
          secret,
          active: !!active
        }
      }
    );
    if (updateResult.ok === 1) {
      await ctx.json(true, '更新秘钥成功');
    } else {
      await ctx.json(false, '更新秘钥失败');
    }
  });

  router.delete('/api/admin/secret/:id', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    let id = ctx.params.id;
    const thisSecret = await Secret.findById(id, '_id');
    if (!thisSecret) {
      await ctx.json(false, '秘钥不存在');
      return false;
    }
    await Secret.deleteOne({
      _id: id
    });
    await ctx.json(true, '删除秘钥成功');
  });

  router.get('/api/front/secret/open', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const bookid = ctx.request.query.bookid;
    const secret = ctx.request.query.secret;
    const thisUser = await User.findById(userid, '_id username');
    if (!thisUser) {
      await ctx.json(false, '用户不存在');
      return false;
    }
    const thisBook = await Book.findById(bookid, '_id name');
    if (!thisBook) {
      await ctx.json(false, '书籍不存在');
      return false;
    }
    const secretReg = /^[A-Za-z0-9_-]{7,14}$/;
    if (!secretReg.test(secret)) {
      await ctx.json(false, '好像不对哦~');
      return false;
    }
    const thisBook2 = await Book.findOne({ _id: bookid, secret }, '_id');
    if (!thisBook2) {
      await ctx.json(false, '好像不对哦~');
      return false;
    }
    const thisSecret = await Secret.create({
      // @ts-ignore
      userid: ctx.transId(userid),
      bookid: ctx.transId(bookid),
      active: true,
      create_time: new Date()
    });
    if (thisSecret) {
      await ctx.json(true, '开始阅读吧~');
    } else {
      await ctx.json(false, '好像不对哦~');
    }
  });

  // 管理员分享的时候预创建一个未解锁的secret
  router.post('/api/front/secret/pre_create', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    // 校验当前用户是否存在分享白名单里
    const shareWhite = await Setting.findOne({ key: 'share_white_list' }, 'value');
    if (!shareWhite) {
      await ctx.json(false, '暂无权限');
      return;
    }
    const shareWhiteList = shareWhite.value;
    if (shareWhiteList.indexOf(userid) < 0) {
      await ctx.json(false, '暂无权限');
      return;
    }
    // 创建secret
    const bookid = ctx.request.body.bookid;
    if (!bookid) {
      await ctx.json(false, '缺乏bookid参数');
      return;
    }
    const book = await Book.findById(bookid, '_id');
    if (!book) {
      await ctx.json(false, 'bookid参数错误');
      return;
    }
    // @ts-ignore
    const newSecret = await Secret.create({ bookid: ctx.transId(bookid), active: false, create_time: new Date() });
    if (newSecret._id) {
      await ctx.json(true, 'success', newSecret._id);
    } else {
      await ctx.json(false, '创建密钥失败');
    }
  });

  // 打开预分享密钥, 为用户自动解锁书籍函数
  router.post('/api/front/secret/pre_secret_open', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const { pre_secret } = ctx.request.body;
    if (!pre_secret) {
      await ctx.json(false, '缺乏pre_secret参数');
      return false;
    }
    const thisUser = await User.findById(userid, '_id username');
    if (!thisUser) {
      await ctx.json(false, '用户不存在');
      return false;
    }
    // @ts-ignore
    const thisSecret = await Secret.findOne({ _id: pre_secret });
    if (!thisSecret) {
      await ctx.json(false, '秘钥参数错误');
      return false;
    }
    if (thisSecret && thisSecret.active) {
      await ctx.json(false, '解锁秘钥已被使用过了', {
        repeat: true,
        isSelf: userid.toString() === thisSecret.userid.toString()
      });
      return false;
    }
    // 检查是否预分享密钥已经使用过了
    const updateResult = await Secret.updateOne(
      { _id: pre_secret },
      {
        $set: {
          userid: ctx.transId(userid),
          active: true
        }
      }
    );
    if (updateResult.ok === 1) {
      await ctx.json(true, '开始阅读吧~');
    } else {
      await ctx.json(false, '好像不对哦~');
    }
  });
}
